<?php

/*	Vulpes-backend - Web-based managegent for wireless internet providers.
	Copyright (C) 2007 LinFox Serviços em Informática Ltda.

	This file is part of the Vulpes backend.

	Vulpes-backend is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Vulpes-backend is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

 	Please note that any front-end (client application) that is distributed
	along with the Vulpes back-end, such as the Vulpes front-end by LinFox,
	is subject to it's correspending licene. */

class user
{
	public $username;
	public $email;
	public $name;
	public $verified = false;
	public $admin = false;
	private $password;
	private $db;

	function __construct($username = false)
	{
		global $db;
		$this->db =& $db;
		$this->verified = $this->verify();
	}
	
	/**
	 * Verifica se o usuario esta autenticado
	 * 
	 * em caso que nao, tenta autenticar usando os valores no $_POST
	 * em caso que o usuario é autenticado, os dados sao guardados nas variaveis desse class
	 */
	function verify()
	{
		global $conf;
		global $page;

		if ($_POST['action'] == 'logout' || $_GET['action'] == 'logout')
		{
			$_SESSION = array();
			session_destroy();
			return false;
		}
		elseif (isset($_POST['username']) && isset($_POST['password']) && $_SESSION['vulpes_user_session'] != true)
		{
			$sql_user = '
				SELECT `username`, `name`, `admin`
				FROM `users`
				WHERE `username` = "' .$this->db->real_escape_string($_POST['username']). '"
					AND `password` = "' .hash('sha512', $_POST['password']). '"';

			if (!$result_user = $this->db->query($sql_user))
				return false;

			if ($result_user->num_rows > 0) {
				$user = $result_user->fetch_object();
				$_SESSION['vulpes_user_session'] = true;
				$_SESSION['vulpes_user_username'] = $user->username;
				$_SESSION['vulpes_user_name'] = $user->name;
				$_SESSION['vulpes_user_admin'] = $user->admin;
				$_SESSION['vulpes_user_email'] = $user->email;
			} else {
				$page->error('{lang_user_not_verified}');
				return false;
			}

			$result_user->free();
		}
		
		if ($_SESSION['vulpes_user_session'] == true)
		{
			$this->username = $_SESSION['vulpes_user_username'];
			$this->nome  = $_SESSION['vulpes_user_name'];
			$this->admin = $_SESSION['vulpes_user_admin'];
			$this->email = $_SESSION['vulpes_user_email'];

			return true;
		}
		else
		{
			return false;
			$page->error('{lang_user_not_verified}');
		}

	}

}

?>